package com.zzw.configuration;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;

//如何配置全局 default-init-method default-destroy-method
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {
        TestConfiguration.TestBean.class,
        TestConfiguration.DefaultInitMethodPostProcessor.class,
})
public class TestConfiguration {

    private static final String DATA = "Hello,World";

    @Autowired
    private TestBean testBean;

    @Test
    public void testValue() {
        Assert.assertEquals(DATA, testBean.value);
    }

    /**
     * 测试 Bean
     */
    public static class TestBean {

        private String value;


        // 被 postProcessMergedBeanDefinition 方法调用
        public void init() {
            System.out.println("字段 value 被初始化");
            this.value = DATA;
        }
    }

    public static class DefaultInitMethodPostProcessor implements MergedBeanDefinitionPostProcessor {

        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            return bean;
        }

        @Override
        public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
            if (TestBean.class.equals(beanType)) { // 设置你需要的 bean
                beanDefinition.setInitMethodName("init"); // 设置 init 方法
            }
        }

    }
}
